﻿using System;
using System.IO;
using System.Linq;
using System.Web.Hosting;
using System.Web.Mvc;
using UIShell.OSGi;

namespace UIShell.OSGI.Mvc
{
    class BundleRazorViewEngine : RazorViewEngine
    {
        private readonly IBundle _bundle;
        protected string SymbolicName
        {
            get { return _bundle.SymbolicName; }
        }

        public BundleRazorViewEngine(IBundle bundle)
        {
            _bundle = bundle;
            var bundleLocation = Path.Combine(@"~\",
                bundle.Location.Replace(HostingEnvironment.ApplicationPhysicalPath, String.Empty));

            AreaViewLocationFormats = AreaViewLocationFormats
                .Select(item => item.Replace("~", bundleLocation)).ToArray();
            AreaMasterLocationFormats = AreaMasterLocationFormats
                .Select(item => item.Replace("~", bundleLocation)).ToArray();
            AreaPartialViewLocationFormats = AreaPartialViewLocationFormats
                .Select(item => item.Replace("~", bundleLocation)).ToArray();
            ViewLocationFormats = ViewLocationFormats
                .Select(item => item.Replace("~", bundleLocation)).ToArray();
            MasterLocationFormats = MasterLocationFormats
                .Select(item => item.Replace("~", bundleLocation)).ToArray();
            PartialViewLocationFormats = PartialViewLocationFormats
                .Select(item => item.Replace("~", bundleLocation)).ToArray();
        }

        public override ViewEngineResult FindView(ControllerContext controllerContext,
            string viewName, string masterName, bool useCache)
        {
            var symbolicName = controllerContext.RouteData.GetPluginSymbolicName();
            if (!string.IsNullOrEmpty(symbolicName) && _bundle.SymbolicName.Equals(symbolicName))
            {
                return base.FindView(controllerContext, viewName, masterName, useCache);
            }
            return new ViewEngineResult(new string[0]);
        }

        public override ViewEngineResult FindPartialView(ControllerContext controllerContext,
            string partialViewName, bool useCache)
        {
            object symbolicName = controllerContext.RouteData.GetPluginSymbolicName();
            if (symbolicName != null && _bundle.SymbolicName.Equals(symbolicName))
            {
                return base.FindPartialView(controllerContext, partialViewName, useCache);
            }
            return new ViewEngineResult(new string[0]);
        }
    }
}
